//
//  CTVAutoSync.m
//  Channltv
//
//  Created by Bruno Keymolen on 08/09/07.
//  Copyright 2007 channl.tv. All rights reserved.
//

#import "CTVAutoSync.h"
#import "CTVSync.h"
#import "CTVAutoUpdate.h"

@implementation CTVAutoSync


+(id)GetInstance{
	static id _CTVSingleton = nil;
	if (_CTVSingleton == nil) {
		_CTVSingleton = [self new];
	}	
    return _CTVSingleton;	
}

-(void)dealloc{
	if(m_timer){
		[m_timer invalidate];
		[m_timer release];
	}
	[super dealloc];
}


-(void)start{
	[self restart];
}


-(void)restart{
	if(m_timer){
		[m_timer invalidate];
		[m_timer release];
		m_timer = nil;
	}	
		
	//Read the number of minutes out of the defaults
	NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
	int timeOutMin = [defaults integerForKey:CTVCONF_AUTOSYNCMIN];
	if(timeOutMin > 0){
		m_timer = [NSTimer scheduledTimerWithTimeInterval:timeOutMin*60.0 target:self selector:@selector(timerHandler:) userInfo:nil repeats:YES];
		[m_timer retain];
	}
}



-(void)timerHandler:(NSTimer*)timer
{
	//Load network data
	[[CTVSync GetInstance] syncWithNetwork];
	
	
	//Check also for new updates (this only sets a flag CTVAutoUpdate::updateAvailable)
	[[CTVAutoUpdate GetInstance] checkNewVersion];

} 


-(void)syncNow{
	if(m_timer != nil){
		[m_timer fire];	
	}else{
		[[CTVSync GetInstance] syncWithNetwork];
	}
}

@end

